package impl

import (
	"NetTools/data"
	"fmt"
	"os/exec"
	"regexp"
	"strings"
	"sync"
)

// DeviceScanner 扫描局域网在线设备
type DeviceScanner struct {
	mu sync.Mutex
}

// NewDeviceScanner 创建新的设备扫描器
func NewDeviceScanner() *DeviceScanner {
	return &DeviceScanner{}
}

// Scan 扫描局域网并返回在线设备列表
func (ds *DeviceScanner) Scan() ([]*data.Device, error) {
	ds.mu.Lock()
	defer ds.mu.Unlock()

	// 执行arp命令
	cmd := exec.Command("arp", "-a")
	output, err := cmd.Output()
	if err != nil {
		return nil, err
	}

	// 解析arp输出
	devices := parseARPOutput(string(output))

	// 添加到DC单例
	dc := data.GetInstance()
	for _, dev := range devices {
		dc.AddDevice(dev)
	}

	return devices, nil
}

// parseARPOutput 解析arp命令输出
func parseARPOutput(output string) []*data.Device {
	var devices []*data.Device
	lines := strings.Split(output, "\n")

	// Windows arp -a输出格式:
	// 接口: 192.168.1.100 --- 0xb
	//   Internet 地址         物理地址              类型
	//   192.168.1.1          00-11-22-33-44-55     动态
	//   192.168.1.255        ff-ff-ff-ff-ff-ff     静态

	// 匹配IP和MAC地址的正则表达式
	re := regexp.MustCompile(`(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F-]+)`)

	for _, line := range lines {
		matches := re.FindStringSubmatch(line)
		if len(matches) == 3 {
			ip := matches[1]
			mac := strings.ToUpper(strings.ReplaceAll(matches[2], "-", ":"))

			// 跳过广播地址
			if ip == "255.255.255.255" || strings.HasSuffix(ip, ".255") {
				continue
			}

			dev := &data.Device{
				IP:     ip,
				MAC:    mac,
				Status: "online",
			}
			devices = append(devices, dev)
		}
	}

	return devices
}

// ScanOnlineDevices 扫描并打印在线设备(供menu.go调用)
func ScanOnlineDevices() error {
	scanner := NewDeviceScanner()
	devices, err := scanner.Scan()
	if err != nil {
		return err
	}

	fmt.Println("在线设备列表:")
	fmt.Println("IP地址\t\tMAC地址\t\t状态")
	fmt.Println("----------------------------------")
	for _, dev := range devices {
		fmt.Printf("%s\t%s\t%s\n", dev.IP, dev.MAC, dev.Status)
	}
	return nil
}
